package com.bocom.hairy.crab.consumer.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 日志拦截器：记录HTTP请求详情（适配Spring Boot 3）
 */
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoggingInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        // 打印请求信息
        log.info("请求URL: {} {}", request.getMethod(), request.getURI());
        log.info("请求头: {}", request.getHeaders());
        if (body.length > 0) {
            String requestBody = new String(body, StandardCharsets.UTF_8);
            log.info("请求体: {}", maskSensitiveInfo(requestBody)); // 脱敏敏感信息
        }

        // 执行请求并记录响应
        long start = System.currentTimeMillis();
        ClientHttpResponse response = execution.execute(request, body);
        long cost = System.currentTimeMillis() - start;

        // 打印响应信息
        log.info("响应状态: {} (耗时: {}ms)", response.getStatusCode(), cost);
        log.info("响应头: {}", response.getHeaders());
        String responseBody = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);
        log.info("响应体: {}", maskSensitiveInfo(responseBody));

        return response;
    }

    // 敏感信息脱敏（如密码、token）
    private String maskSensitiveInfo(String content) {
        return content.replaceAll("\"password\":\"[^\"]+\"", "\"password\":\"***\"")
                .replaceAll("\"token\":\"[^\"]+\"", "\"token\":\"***\"");
    }
}

